#include <iostream>
#include <thread>
using namespace std;
//懒汉模式实现线程安全
class singleton{
public:
   static singleton* getInstance(){
    pthread_once(&_once,init);
       return _ps;
    }
    singleton(const singleton& rhs)=delete;
    singleton& operator=(const singleton& rhs)=delete;

    
    class autorelease{
    public:
        ~autorelease(){
            
                cout<<"~autorelease"<<endl;
            if(_ps){
                delete  _ps;
                _ps=nullptr;
            }
        }
};
private:
static void init(){
    if(!_ps){
    _ps=new singleton();
    }
}
singleton(){
    cout<<"singleton"<<endl;
}
~singleton(){
    cout<<"~singleton"<<endl;
}
    static singleton* _ps;
    static autorelease _ar;
    static pthread_once_t _once;
    };
    pthread_once_t singleton::_once=PTHREAD_ONCE_INIT;
    singleton* singleton::_ps=nullptr;
    singleton:: autorelease singleton ::_ar;
    
    void test(){
    //怎么用
        singleton* p=singleton::getInstance();
        
        singleton* p2=singleton::getInstance();
    }
    
int main(int argc, char * argv[]){
    test();
    return 0;
}

